package com.api.syh56.shengyunhui.service.impl;

import cn.jiguang.sdk.api.DeviceApi;
import cn.jiguang.sdk.api.PushApi;
import cn.jiguang.sdk.bean.push.PushSendParam;
import cn.jiguang.sdk.bean.push.PushSendResult;
import cn.jiguang.sdk.bean.push.audience.Audience;
import cn.jiguang.sdk.bean.push.message.notification.NotificationMessage;
import cn.jiguang.sdk.bean.push.options.Options;
import cn.jiguang.sdk.constants.ApiConstants;
import cn.jiguang.sdk.enums.platform.Platform;
import cn.jiguang.sdk.exception.ApiErrorException;
import com.api.syh56.shengyunhui.exception.BaseException;
import com.api.syh56.shengyunhui.service.JpushService;
import com.api.syh56.shengyunhui.util.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class JpushServiceImpl implements JpushService {


    @Autowired
    private PushApi pushApi;
    @Autowired
    private DeviceApi deviceApi;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RedisUtil redisUtil;
    @Async
    @Override
    public void pushMessageToUserId(Long userId, String title, String content) {

        Set<Object> members = redisUtil.members(userId.toString());
        log.info("userId:{}", userId);
//        for (Object registrationIdObject : members) {
//            String registrationId = (String) registrationIdObject;
//            log.info("registrationId:{}", registrationId);
//        }
        List<String> registrationIdList = new ArrayList<>();
        for (Object member : members) {
            log.info("registrationId:{}", member);
            if (member instanceof String) {
                registrationIdList.add((String) member);
            }
        }
        System.out.println("registrationIdList:"+registrationIdList);

//        registrationIdList.add("1507bfd3f6f0896bd82");
//        registrationIdList.add("170976fa8bb7f9062cb");//139
//        registrationIdList.add("140fe1da9f9fc01762a");//186


        PushSendParam param = new PushSendParam();
        // 通知内容
        NotificationMessage.Android android = new NotificationMessage.Android();
        android.setAlert(content);
        android.setTitle(title);

        NotificationMessage.IOS iOS = new NotificationMessage.IOS();
        Map<String, String> iOSAlert = new HashMap<>();
        iOSAlert.put("title", title);
        iOSAlert.put("subtitle", content);
        iOS.setAlert(iOSAlert);
        iOS.setSound("default");

//        NotificationMessage.HMOS hmos = new NotificationMessage.HMOS();
//        hmos.setAlert(content);
//        hmos.setTitle(title);
//
//        NotificationMessage.QuickApp quickapp = new NotificationMessage.QuickApp();
//        quickapp.setAlert(content);
//        quickapp.setTitle(title);

//        Map<String, Object> extrasMap = new HashMap<>();
//        Map<String, Object> extrasParamMap = new HashMap<>();
//        extrasParamMap.put("key1", "value1");
//        extrasParamMap.put("key2", "value2");
//        extrasMap.put("params", extrasParamMap);
//        android.setExtras(extrasMap);
//        iOS.setExtras(extrasMap);

        NotificationMessage notificationMessage = new NotificationMessage();
        notificationMessage.setAlert(content);
        notificationMessage.setAndroid(android);
        notificationMessage.setIos(iOS);
//        notificationMessage.setHmos(hmos);
//        notificationMessage.setQuickApp(quickapp);
        param.setNotification(notificationMessage);

        // 目标人群
        Audience audience = new Audience();

        if (registrationIdList.isEmpty()){
            System.out.println(userId+"用户暂无registrationId设备在线");
            return;
        }

        audience.setRegistrationIdList(registrationIdList);
//        audience.setRegistrationIdList(Arrays.asList("1507bfd3f6f0896bd82"));
//        audience.setRegistrationIdList(Arrays.asList("1104a89793af2cfc030", "1104a89793af2cfc030"));

        // 指定目标
         param.setAudience(audience);


        // 或者发送所有平台
         param.setPlatform(ApiConstants.Platform.ALL);

        // Android厂商
        // param.setThirdNotificationMessage();

        // options
        Options options = new Options();
        options.setApnsProduction(true);
        options.setClassification(1);
        // 厂商通道
        /**distribution
         * 取值不能为空字符串。
         * first_ospush（VIP）：成功注册厂商通道的设备走厂商通道，仅注册极光通道的设备走极光通道。
         * ospush（VIP）：表示推送强制走厂商通道下发。 需要特别注意，只要指定此值的厂商对应配额不够时，推送请求会失败，返回 1012 错误码。
         * 举例：假设指定一个小米用户的 RegistrationID 推送，请求时针对小米、OPPO 等厂商通道都指定了“ospush”，且 OPPO 厂商通道都配额已经用完，则推送同样会返回 1012 错误，提示厂商配额不足。
         * jpush：表示推送强制走极光通道下发。
         * secondary_push：表示推送优先走极光，极光不在线再走厂商，厂商作为辅助（建议此种方式）。
         */
        /**distribution_fcm
         * 取值不能为空字符串。
         * jpush：表示推送强制走极光通道下发。
         * fcm（VIP）：表示推送强制走 fcm 通道下发。
         * pns（VIP）：表示推送强制走小米 / 华为 / 荣耀 / 魅族 /oppo/vivo 通道下发。
         * secondary_fcm_push：表示针对 fcm+ 国内厂商组合类型用户，推送优先走极光，极光不在线再走 fcm 通道，fcm 作为辅助。
         * secondary_pns_push：表示针对 fcm+ 国内厂商组合类型用户，推送优先走极光，极光不在线再走厂商通道，厂商作为辅助。
         */
        Map<String, Object> ThirdPartyChannel = new HashMap<>();
        // xiaomi、huawei、honor、meizu、oppo、vivo、fcm
        Map<String, Object> xiaomi = new HashMap<>();
        xiaomi.put("distribution", "first_ospush");
        xiaomi.put("distribution_fcm", "fcm");
        xiaomi.put("channel_id","125720");
        ThirdPartyChannel.put("xiaomi", xiaomi);

        Map<String, Object> huaweiMap = new HashMap<>();
        huaweiMap.put("distribution", "first_ospush");
        huaweiMap.put("distribution_fcm", "fcm");
        huaweiMap.put("category", "EXPRESS");
        ThirdPartyChannel.put("huawei", huaweiMap);

        Map<String, Object> honor = new HashMap<>();
        honor.put("distribution", "first_ospush");
        honor.put("distribution_fcm", "fcm");
        honor.put("importance","NORMAL");
        ThirdPartyChannel.put("honor", honor);

        Map<String, Object> meizu = new HashMap<>();
        meizu.put("distribution", "first_ospush");
        meizu.put("distribution_fcm", "fcm");
        ThirdPartyChannel.put("meizu", meizu);

        Map<String, Object> oppo = new HashMap<>();
        oppo.put("distribution", "first_ospush");
        oppo.put("distribution_fcm", "fcm");
        oppo.put("channel_id","125720");
        ThirdPartyChannel.put("oppo", oppo);
//
        Map<String, Object> vivo = new HashMap<>();
        vivo.put("distribution", "first_ospush");
        vivo.put("distribution_fcm", "fcm");
        vivo.put("category", "ORDER");
        ThirdPartyChannel.put("vivo", vivo);
//        Map<String, Object> fcm = new HashMap<>();
//        fcm.put("distribution", "jpush");
//        ThirdPartyChannel.put("fcm", fcm);

        options.setThirdPartyChannel(ThirdPartyChannel);

        param.setOptions(options);
        log.info("param:" + param);
        // 发送
        try{
            PushSendResult result = pushApi.send(param);
            log.info("极光推送result:{}", result);
        }catch (ApiErrorException e){
            log.info("stats:{}",e.getStats());
            log.info("message:{}",e.getMessage());
            log.info("ApiEro:{}",e.getApiError());
//            System.out.println(e.getStats());
//            System.out.println(e.getMessage());
//            System.out.println(e.getApiError());
        }

        log.info("各平台参数:{}",ThirdPartyChannel);
        log.info(userId+" 极光推送已发送消息给:{}",registrationIdList);

        return;
    }
}
